﻿using BaseData.API.Read.Applications.HospitalInformation.Command;
using BaseData.API.Read.Dtos;
using BaseData.Domain.HospitalInformation;
using BaseData.ErrorCode;
using BaseData.Infrastructure.Interfaces;
using Essensoft.Paylink.Alipay.Domain;
using MediatR;
using NPOI.POIFS.Properties;
using System.Collections.Generic;

namespace BaseData.API.Read.Applications.HospitalInformation.CommandHandler
{
    public class DepartmentsShowCommandHandler : IRequestHandler<DepartmentsShowCommand, ApiResult<ApiPaging<Departments>>>
    {
        IBaseRepository<Departments> repository;

        public DepartmentsShowCommandHandler(IBaseRepository<Departments> repository)
        {
            this.repository = repository;
        }

        public async Task<ApiResult<ApiPaging<Departments>>> Handle(DepartmentsShowCommand request, CancellationToken cancellationToken)
        {
            var res = from a in repository.GetAll().Where(x => !x.Isdelete)
                      join b in repository.GetAll().Where(x => !x.Isdelete)
                      on a.parentId equals b.DepartmentId
                      into d
                      from b in d.DefaultIfEmpty()
                      select new Departments
                      {
                            DepartmentId=a.DepartmentId,
                            DepartmentName=a.DepartmentName,
                            HospitalCampus=a.HospitalCampus,
                            parentId=a.parentId,
                            SuperiorDepartment = b==null?"":b.DepartmentName,
                            DepartmentAdd=a.DepartmentAdd,
                            DepartmentStatus=a.DepartmentStatus,
                            Isdelete=a.Isdelete,

                      };

            if (!string.IsNullOrEmpty(request.DepartmentName))
            {
                res = res.Where(x => x.DepartmentName.Contains(request.DepartmentName));
            }
            if(request.parentId!=null)
            {
                res = res.Where(x => x.parentId == (request.parentId));
            }
            int TotalCount = res.Count();
            int PageCount = (int)Math.Ceiling(TotalCount*1.0 / request.PageSize);
            res = res.OrderBy(x => x.DepartmentId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            return new ApiResult<ApiPaging<Departments>>()
            {
                Message=ApiEnum.查询成功.ToString(),
                Code=ApiEnum.查询成功,
                Data=new ApiPaging<Departments>()
                {
                    TotalCount=TotalCount,
                    PageCount=PageCount,
                    Data=res.ToList()
                }
            };
        }
    }
}
